package demon;

import java.util.Arrays;

public class MyArrayList implements IMyArrayList{
    private int useSize;
    private int val;
    private int[]arr;
    public MyArrayList(int val){
        this.val=val;
        arr=new int[10];
    }
    public boolean isFull(){
        if(this.useSize==arr.length){
            return true;
        }
        return false;
    }
    public void Expand(){
        this.arr= Arrays.copyOf(this.arr,this.arr.length*2);
    }
    public void checkPos(int pos){
        if(pos<0||pos>useSize){
            throw new PosException("pos位置不合法");
        }
    }

    @Override
    public void add(int data) {
        if(isFull()){
            Expand();
        }
        this.arr[this.useSize]=data;
        this.useSize++;
    }

    @Override
    public void add(int pos, int data) {
        try{
            checkPos(pos);
        }catch (PosException e){
            e.printStackTrace();
        }
        if(isFull());
        for (int i = this.useSize-1; i <=pos ; i--) {
            this.arr[i+1]=this.arr[i];
        }
        this.useSize++;
    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if(arr[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if(this.arr[i]==toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        try{
            checkPos(pos);
        }catch (PosException e){
            e.printStackTrace();
        }
        return this.arr[pos];
    }

    @Override
    public void set(int pos, int value) {
        try {
            checkPos(pos);
        }catch (PosException e){
            e.printStackTrace();
        }
        this.arr[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        int pos=indexOf(toRemove);
        if(pos==-1){
            return;
        }
        for (int i = pos; i < this.useSize-1; i++) {
            this.arr[i]=this.arr[i+1];
        }
        this.useSize--;
    }

    @Override
    public int size() {
        int count=0;
        for (int i = 0; i < this.useSize; i++) {
            count++;
        }
        return count;
    }

    @Override
    public void clear() {
        this.useSize=0;
    }

    @Override
    public void display() {
        for (int i = 0; i < this.useSize; i++) {
            System.out.print(this.arr[i]+" ");
        }
    }
}
